# 姓名:刘豹
#  开发时间: 2021/4/28 14:19
import cv2
import numpy as np
import matplotlib.pyplot as plt
from pic_utils import pic_tools
from math import pi
img = cv2.imread('D:\python\workspace\insects_detection\processed_imgs\\5-1-2-A.jpg')  #导入图片，图片放在程序所在目录
def extract_hue_characteristics(img):
    Prewitt=pic_tools.prewitt_operator(img)
    contours=pic_tools.getContours(Prewitt)
    count=0
    margin = 5
    X_train = np.empty(shape=[0, 13])
    #遍历找到的所有昆虫
    for cont in contours:
        ares = cv2.contourArea(cont)#计算包围性状的面积
        if ares<10 or ares>120:   #过滤面积小于10的形状
            continue
        count+=1    #总体计数加1
        rect = cv2.minAreaRect(cont)
        box = np.int0(cv2.boxPoints(rect))
        rect_w, rect_h = int(rect[1][0]) + 1, int(rect[1][1]) + 1
        h, w = img.shape[:2]
        if rect_w <= rect_h:
            x, y = box[1][0], box[1][1]
            M2 = cv2.getRotationMatrix2D((x, y), rect[2], 1)
            rotated_image = cv2.warpAffine(img, M2,(w,h))
            rotated_canvas = rotated_image[y:y + rect_h + margin + 1, x:x + rect_w + margin + 1]
        else:
            x, y = box[2][0], box[2][1]  # 旋转中心
            M2 = cv2.getRotationMatrix2D((x, y), rect[2] + 90, 1)
            rotated_image = cv2.warpAffine(img, M2,(w,h))
            rotated_canvas = rotated_image[y:y + rect_w + margin + 1, x:x + rect_h + margin + 1]

        if rotated_canvas.shape[0]==0 or rotated_canvas.shape[1]==0:
            continue
        Perimeter = cv2.arcLength(cont, True)  # 计算目标啊的周长
        Complexity = (Perimeter ** 2 / (4 * pi * ares))  # 计算目标的复杂度
        dutycycle = ares / (rect[1][0] * rect[1][1])  # 计算害虫的占空比
        count += 1  # 总体计数加1
        b, g, r = cv2.split(rotated_canvas)
        b_mean = np.mean(b)
        g_mean = np.mean(g)
        r_mean = np.mean(r)
        rotated_canvas_HSV = cv2.cvtColor(rotated_canvas, cv2.COLOR_BGR2HSV)
        h, s, v = cv2.split(rotated_canvas_HSV)
        h_mean = np.mean(h)
        s_mean = np.mean(s)
        v_mean = np.mean(v)
        rotated_canvas_LAB = cv2.cvtColor(rotated_canvas, cv2.COLOR_BGR2LAB)
        L, A, B = cv2.split(rotated_canvas_LAB)
        L_mean = np.mean(L)
        A_mean = np.mean(A)
        B_mean = np.mean(B)
        X_train = np.append(X_train, [
            [b_mean, g_mean, r_mean, h_mean, s_mean, v_mean, L_mean, A_mean, B_mean, ares, Perimeter, Complexity,
             dutycycle]], axis=0)
    return X_train
print(extract_hue_characteristics(img))





